package com.block.datapush.form.item;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.service.LogFactory;
import com.block.common.util.HmacHanlder;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.item.util.DianDaiUtil;
import com.block.datapush.form.item.util.YiJieUtil;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 易借
 * https://loan.top0.net/
 * https://loan.top0.net/api/third/check_loan?server=1
 * https://loan.top0.net/api/third/loan_do?server=1
 * <p>
 * channel: TestChannel
 * apiKey: testApiKey
 * iv: ZuiX6uVDHmFBJytD
 * factor: tVhNbn86r3R0
 */
@Service
public class YiJiePushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getPushLog();

    /**
     * @param formInfo
     * @param memberExtInfo
     * @return
     */
    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) throws Exception {

        String queryUrl = formInfo.getQueryUrl();
        String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("type", 102);
        dataMap.put("mobileMd5", mobileMd5);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channel", formInfo.getApiCode());
        paramMap.put("data", dataMap);

        log.info("【易借】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}",
                queryUrl, JSON.toJSONString(mobileMd5), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【易借】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");

        if (ObjectUtil.equals(Integer.valueOf(0), code)) {
            return true;
        }
        return false;
    }

    /**
     * /api/Infos/receive
     *
     * @param formInfo
     * @param memberExtInfo
     * @param orderNo
     * @param jsonObject
     * @return
     */
    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject jsonObject) throws Exception {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);

        String queryUrl = formInfo.getRequestUrl();

        Map<String, Object> bizParamMap = new HashMap<>();

        bizParamMap.put("name", memberExtInfo.getUsername());
        bizParamMap.put("age", memberExtInfo.getAge());
        bizParamMap.put("sex", memberExtInfo.getSex());
        bizParamMap.put("phone", memberExtInfo.getMobile());
        bizParamMap.put("id_code", memberExtInfo.getIdCard());
        bizParamMap.put("city", memberExtInfo.getCity());

        bizParamMap.put("house", YiJieUtil.getHouse(memberExtInfo.getHouse()));
        bizParamMap.put("car", YiJieUtil.getCar(memberExtInfo.getCar()));
        bizParamMap.put("occupation", 1);
        bizParamMap.put("social_security", YiJieUtil.getSheBao(memberExtInfo.getSocialInsurance()));
        bizParamMap.put("reserved_funds", YiJieUtil.getGjj(memberExtInfo.getGjj()));
        bizParamMap.put("life_insurance", YiJieUtil.getBaoXian(memberExtInfo.getInsurance()));
        bizParamMap.put("zm_score", YiJieUtil.getZhima(memberExtInfo.getZhimaScore()));
        bizParamMap.put("quota", BaseTypeInfoEnum.LoanAmount.getEntryByValue(memberExtInfo.getLoanAmount()).getAmount());

        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, StrUtil.bytes(formInfo.getApiKey()), StrUtil.bytes(formInfo.getApiSecret()));
        String content = aes.encryptBase64(JSON.toJSONString(bizParamMap));

        String sign = new HmacHanlder(formInfo.getPubKey()).encrypt(JSON.toJSONString(bizParamMap) + "_" + formInfo.getPubKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sign", sign);
        paramMap.put("content", content);
//        paramMap.put("content", JSON.toJSONString(bizParamMap));
//        paramMap.put("orderNo", orderNo);

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Channel-ID", formInfo.getApiCode());
        headMap.put("Content-Type", "application/json");

        log.info("【易借】导单开始【queryUrl】{}【headMap】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(headMap),  JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .headerMap(headMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【易借】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        pushResultDTO.setResult(result);
        pushResultDTO.setCode(String.valueOf(code));
        pushResultDTO.setMessage(UnicodeUtil.toString(message));
        pushResultDTO.setParamContent(JSON.toJSONString(bizParamMap));

        if (ObjectUtil.equal(code, Integer.valueOf(1))) {
            pushResultDTO.setPushResult(PushResultEnum.SUCCESS.getType());
            pushResultDTO.setSuccess(true);// 不接算
        } else {
            pushResultDTO.setPushResult(PushResultEnum.FAILED.getType());
            pushResultDTO.setSuccess(false);
        }
        return pushResultDTO;

    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }

}
